package com.inspur.pim.cbb.maintenance.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.nio.channels.FileChannel;

/***
 * @description
 * @author jiaxinxin
 * @date 2020/12/16 17:30
 */
public class FileUtils {
    static Logger LOG = LoggerFactory.getLogger(FileUtils.class);

    public static void copyFile(String targetFilePath, String sourceFilePath) throws Exception {
        FileChannel sourceChannel = null;
        FileChannel targetChannel = null;
        FileInputStream fileInputStream = null;
        FileOutputStream fileOutputStream = null;
        File sourceFile = null;
        File targetFile = null;
        try {
            sourceFile = new File(sourceFilePath);
            targetFile = new File(targetFilePath);
            fileInputStream = new FileInputStream(sourceFile);
            fileOutputStream = new FileOutputStream(targetFile);
            sourceChannel = fileInputStream.getChannel();
            targetChannel = fileOutputStream.getChannel();
            sourceChannel.transferTo(0, sourceChannel.size(), targetChannel);

        } catch (Exception e) {
            LOG.error(e.getMessage());
            throw new Exception();
        } finally {
            try {
                if (fileInputStream != null) {
                    fileInputStream.close();
                }
                if (fileOutputStream != null) {
                    fileOutputStream.flush();
                    fileOutputStream.close();
                }
                if (sourceChannel != null) {
                    sourceChannel.close();
                }
                if (targetChannel != null) {
                    targetChannel.close();
                }
            } catch (Exception e) {
                LOG.error(e.getMessage());
            }
        }
    }

    public static boolean writeFile(File file, String content) {
        FileWriter writer = null;
        try {
            writer = new FileWriter(file);
            writer.write(content);
        } catch (IOException e) {
            LOG.error(e.getMessage());
            return false;
        } finally {
            if (writer != null) {
                try {
                    writer.close();
                } catch (IOException e) {
                    LOG.error(e.getMessage());
                }
            }
        }

        return true;

    }


}
